<template>
	<div>
		<div class="app-container">
			<TopInfo />
			<el-button type="primary" size="small" @click="add('')">
				<template #default>
					<span class="text-sm">{{ $t('account.authority.add') }}</span>
				</template>
			</el-button>
		</div>

		<div class="app-container" v-loading="data.mtloading">
			<el-row :gutter="20">
				<el-col :span="6"><div class="grid-content ep-bg-purple" />
					<el-tree
					style="max-width: 600px"
					:props="props"
					:load="loadNode"
					lazy
					@node-click="nodeClick"
					:highlight-current="true"
				>
				<template #default="{ node, data }">
					<div class="custom-tree-node">
					<span>{{ node.label }}</span>
					<div>
						<el-button type="success" link @click="add(data)" :icon="Plus" />
						<el-button type="primary" link @click="modify(data)" :icon="Edit" />
						<el-button type="danger" link @click="del(data.node_id)" :icon="Delete" />
					</div>
					</div>
				</template>
					</el-tree>
				</el-col>
				<el-col :span="18" v-if="data.level3list.length">
					<el-table ref="cTable" :data="data.level3list" :header-cell-style="{ 'text-align': 'center' }"
						:cell-style="{ 'text-align': 'center' }" class="w-full" lazy :load="load"
						:tree-props="{ hasChildren: 'hasChildren' }" row-key="node_id" stripe>
						<el-table-column width="120" />
						<el-table-column prop="node_id" label="ID" show-overflow-tooltip />
						<el-table-column prop="name" :label="$t('account.authority.nodeName')" show-overflow-tooltip>
							<template #default="scope">
								{{ scope.row.name || '--' }}
							</template>
						</el-table-column>
						<el-table-column prop="url" :label="$t('account.authority.nodeRoute')" show-overflow-tooltip>
							<template #default="scope">
								{{ scope.row.url || '--' }}
							</template>
						</el-table-column>
						<el-table-column prop="sort" :label="$t('account.authority.nodeSort')" show-overflow-tooltip>
							<template #default="scope">
								{{ scope.row.sort || '0' }}
							</template>
						</el-table-column>
						<el-table-column prop="type" :label="$t('account.authority.nodeType')" show-overflow-tooltip>
							<template #default="scope">
								<el-link v-if="scope.row.type == 1" type="success" :underline="false">{{
									$t('account.authority.menuNode') }}</el-link>
								<el-link v-if="scope.row.type == 2" type="primary" :underline="false">{{
									$t('account.authority.InterNode') }}</el-link>
								<el-link v-if="scope.row.type == 3" type="warning" :underline="false">{{
									$t('account.authority.authority') }}</el-link>
							</template>
						</el-table-column>
						<el-table-column prop="status" :label="$t('account.authority.nodeStatus')" show-overflow-tooltip>
							<template #default="scope">
								<el-tag v-if="scope.row.status == 1" type="success">{{ $t('public.enable') }}</el-tag>
								<el-tag v-if="scope.row.status == 2" type="danger">{{ $t('public.disable') }}</el-tag>
							</template>
						</el-table-column>
						<el-table-column prop="is_button" :label="$t('account.authority.isButton')" show-overflow-tooltip>
							<template #default="scope">
								<el-tag v-if="scope.row.is_button == 1">{{ $t('public.yes') }}</el-tag>
								<el-tag v-if="scope.row.is_button == 2" type="info">{{ $t('public.no') }}</el-tag>
							</template>
						</el-table-column>
						<el-table-column prop="data_auth" :label="$t('account.authority.authority')" show-overflow-tooltip>
							<template #default="scope">
								<el-tag v-if="scope.row.data_auth == 1">{{ $t('public.yes') }}</el-tag>
								<el-tag v-if="scope.row.data_auth == 2" type="info">{{ $t('public.no') }}</el-tag>
							</template>
						</el-table-column>
						<el-table-column :label="$t('public.operate')" width="200">
							<template #default="scope">
								<el-button type="success" size="small" @click="add(scope.row)" :icon="Plus"/>
								<el-button type="primary" size="small" @click="modify(scope.row)" :icon="Edit"/>
								<el-button v-prmis="'auth_node_del'" type="danger" size="small" @click="del(scope.row.node_id)" :disabled="scope.row.hasChildren" :icon="Delete"/>
							</template>
						</el-table-column>
					</el-table>
				</el-col>
			</el-row>
		</div>
	</div>
</template>

<script lang="ts" setup>
import { useI18n } from 'vue-i18n'
const { t: $t } = useI18n()
import {
  Plus,
  Delete,
  Edit,
} from '@element-plus/icons-vue'
import TopInfo from '@/components/TopInfo/index.vue';
import { getauthnodeList, delauthnode } from '@/api/account';
import { useRouter } from "vue-router";
const router = useRouter()
const cTable = ref(null)

let data = reactive({
	level3list: [],
	mtloading: false, // 加载
	lookup: [ // 筛选栏
		{ title: $t('account.authority.nodeName'), type: 'input', value: '', key: 'name' },
		{ title: $t('account.authority.nodeType'), type: 'define', select: [{ label: $t('public.menu'), value: 1 }, { label: $t('public.pages'), value: 2 },], value: '', key: 'type' },
		{ title: $t('account.authority.nodeStatus'), type: 'define', select: [{ label: $t('public.enable'), value: 1 }, { label: $t('public.prohibit'), value: 2 },], value: '', key: 'status' },
	],
	list: [], // 列表信息

	treeLoad: [], // 懒加载子级菜单
	Loadstatus: false, // 懒加载状态
	Loadnum: 0, // 加载数量

	authnode: {
		name: '',
		type: '',
		status: '',
		pid: '0',
	}
})
const props = {
  label: 'name',
  value:'node_id',
  children: 'zones',
  isLeaf: 'leaf',
}
const nodeClick = async(val:any) =>{
	if(val.pid !== 0){
		await findauthnodeList(val.node_id).then(res=>{
			data.level3list = res
		})
	}else{
		data.level3list = []
	}
}
const findauthnodeList =(node_id:any)=>{
	return getauthnodeList({ pid:node_id }).then(res => {
		const list = []
		data.mtloading = false
		if (res.state == 200) {
			for (let item of res.data) {
				item.hasChildren = true
				list.push(item)
			}
		}
		return list
	})
}
const loadNode =async (node: Node, resolve: (datas:any) => void) => {
  if (node.level === 0) {
	await getauthnodeList(data.authnode).then(res => {
		data.mtloading = false
		if (res.state == 200) {
			for (let item of res.data) {
				item.hasChildren = true
				data.list.push(item)
			}
		}
	})
    return resolve(data.list)
  }
  if (node.level > 2) return resolve([])
  	setTimeout(async() => {
		let list = await findauthnodeList(node.data.node_id)
		if(node.level == 2){
			data.level3list = list
			resolve([])
		}else{
			resolve(list)
		}
  }, 500)
}

// 获取列表信息
let getlist = () => {
	data.mtloading = true
	data.list = []
	getauthnodeList(data.authnode).then(res => {
		data.mtloading = false
		if (res.state == 200) {
			for (let item of res.data) {
				item.hasChildren = true
				data.list.push(item)
			}
		}
	})
}

// 查询回调
let inves = (e) => {
	for (let key in e) {
		data.authnode[key] = e[key]
	}
	getlist()
}

// 添加权限
let add = (e) => {
	let query = {
		l: encodeURI(JSON.stringify({
			info: e
		}))
	}
	router.push({ path: '/account/authority/add_info', query: query })
}

// 修改权限
let modify = (e) => {
	let query = {
		l: encodeURI(JSON.stringify({
			info: e
		}))
	}
	router.push({ path: '/account/authority/details_info', query: query })
}

// 删除权限
let del = (e) => {
	ElMessageBox.confirm($t('message.deleteInfo'))
		.then(res => {
			delauthnode({ 'node_id': e }).then(res => {
				if (res.state == 200) {
					ElMessage({
						message: $t('message.delSuccess'),
						type: 'success'
					})
					subordinate(e)
					return
				}
				ElMessage({
					message: $t('message.networkFailed'),
					type: 'error'
				})
			})
		}).catch(err => {
			console.log('取消')
		})
}

// 树状懒加载
let load = (row, treeNode, resolve) => {
	let arr = []
	if (data.Loadstatus == false) {
		data.treeLoad.push({ row, treeNode, resolve })
	}

	getauthnodeList({ pid: row.node_id }).then(res => {
		if (res.state == 200) {
			for (let item of res.data) {
				item.hasChildren = true
				arr.push(item)
			}
		}

		if (arr.length == 0) {
			row.hasChildren = false
		}

		if (data.Loadstatus) {
			data.Loadnum = 0
			data.Loadstatus = false
		}
		resolve(arr)
	}).catch(err => {
		resolve([])
		row.hasChildren = false
		// 修复表格删除最后一条时，依旧存在数据问题
		cTable.value.store.states.lazyTreeNodeMap.value[row.node_id] = [];
	})

}

// 刷新子级节点
let subordinate = (e) => {
	let obj = {}
	for (let item of data.treeLoad) {
		if (item.row.node_id == e) {
			obj = item
		}
	}

	if (obj.row != undefined) {
		for (let item of data.treeLoad) {
			if (item.row.node_id == obj.row.pid) {
				obj = item
			}
		}
		data.Loadstatus = true
		data.Loadnum = data.treeLoad.length
		obj.treeNode.loading = true
		load(obj.row, obj.treeNode, obj.resolve)
	}
}

// getlist()

</script>
<style lang="scss">
.custom-tree-node {
  flex: 1;
  display: flex;
  align-items: center;
  justify-content: space-between;
  font-size: 14px;
  padding-right: 8px;
}
.el-table_1_column_1 {
	text-align: left !important;
}

.el-table__row--level-1 {
	.el-table__cell {
		text-align: center !important;
	}
}

.el-table__row--level-2 {
	.el-table__cell {
		text-align: right !important;
	}
}

.el-table__row--level-3 {
	.el-table__cell {
		text-align: right !important;
	}
}
</style>
